(function () {
  $(function () {
    var AssetsHandler = function (el, tempEl, paginationEl, paginationTempEl) {
      var storage = {
        el: $(el),
        tempEl: $(tempEl),
        paginationEl: $(paginationEl),
        paginationTempEl: $(paginationTempEl),
        page: 1,
        totalPage: 1
      }
      if (!storage.el || !storage.tempEl) {
        alert('请正确设置')
        return
      }
      return {
        getCurrentPage: function () {
          return storage.page
        },
        getAsserts: function (page) {
          var _this = this
          // 这里进行异步请求获取。
          $.ajax({
            url: '../../../assets.json',
            type: 'GET',
            success: function (res) {
              console.log(res)
              // 渲染列表
              _this.renderPage(res.data)
              // 重新渲染分页器
              _this.renderPagination(page, res.totalPage)
            }
          })
          // 示例
          // $.ajax({
          //   url: 'xxx',
          //   type: 'POST',
          //   data: {page: page},
          //   success: function(res) {
          //     console.log(res)
          //     _this.renderPage(res.data)
          //      重新渲染分页器
          //     _this.renderPagination(page, res.totalPage)
          //   }
          // })
        },
        changePage: function (page) {
          // 用于切换页面
          storage.page = page
          this.getAsserts(storage.page)
        },
        renderPage: function (data) {
          // 渲染列表
          var resource = storage.tempEl.html()
          var html = template.render(resource, { data: data });
          storage.el.html(html)
        },
        renderPagination: function (page, totalPage) {
          // 渲染分页器
          console.log('set page: ', page)
          console.log('set totalPage: ', totalPage)
          var resource = storage.paginationTempEl.html()
          var html = template.render(resource, { page: page, totalPage: totalPage, arr: new Array(totalPage) });
          storage.paginationEl.html(html)
        },
        initPage: function () {
          // 初始化
          console.log('page has been initialized')
          this.getAsserts(storage.page)
        }
      }
    }
    var asset = new AssetsHandler('#assets-list', '#assets-list-item-template', '#pagination', '#pagination-template')
    asset.initPage()
    $('#pagination').on('click', '.page', function () {
      var page = $(this).data('page')
      asset.changePage(page)
    })
    $('#pagination').on('click', '.perv', function () {
      var page = asset.getCurrentPage()
      asset.changePage(page - 1)
    })
    $('#pagination').on('click', '.next', function () {
      var page = asset.getCurrentPage()
      asset.changePage(page + 1)
    })
  })
})()